package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * IOT设备产品表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询IOT设备产品表
     * 
     * @param id IOT设备产品表主键
     * @return IOT设备产品表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询IOT设备产品表列表
     * 
     * @param device IOT设备产品表
     * @return IOT设备产品表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增IOT设备产品表
     * 
     * @param device IOT设备产品表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改IOT设备产品表
     * 
     * @param device IOT设备产品表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除IOT设备产品表
     * 
     * @param ids 需要删除的IOT设备产品表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除IOT设备产品表信息
     * 
     * @param id IOT设备产品表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 同步产品列表到redis中
     */
    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse listProductsResponse = client.listProducts(request);
        if(listProductsResponse.getHttpStatusCode()!=200){
            throw new BaseException("网络开小差了");
        }
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(listProductsResponse.getProducts()));
    }

    /**
     * 查询所有产品
     * @return 产品对象VO的集合
     */
    @Override
    public List<ProductVo> getAllProduct() {
        String jsonStr = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        if(jsonStr==null){
            throw new BaseException("未查询到数据");
        }
        return JSONUtil.toList(jsonStr,ProductVo.class);
    }

    @Override
    @Transactional
    public void register(DeviceDto dto) {
        //判断当前设备名称是否重复
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if(count>0){
            throw new BaseException("设备重复,无法申请");
        }
        //判断当前设备标识是否重复
        this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId,dto.getNodeId()));
        if(count>0){
            throw new BaseException("设备重复,无法申请");
        }
        checkSameLocationIsOrNotBingdingSameDevice(dto);
        //注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        AuthInfo authInfo = new AuthInfo();
        //生成随机UUID密钥
        String Secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.setSecret(Secret);
        //封装请求参数
        body.setAuthInfo(authInfo);
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());
        body.setProductId(dto.getProductKey());
        request.setBody(body);
        //发起申请
        AddDeviceResponse response = client.addDevice(request);
        if(response.getHttpStatusCode()!=201){
            throw new BaseException("设备注册失败");
        }
        //保存至数据库
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(Secret);
        device.setIotId(response.getDeviceId());
        this.save(device);
    }

    @Override
    public DeviceDetailVo getDeviceDetailInfo(String iotId) {
        //先查询数据库
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(ObjectUtil.isEmpty(device)){
            throw new BaseException("未查询到相关结果");
        }
        //再查华为云返回激活时间和激活状态
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        String activeTime = response.getActiveTime();
        String status = response.getStatus();
        //封装VO对象返回
        DeviceDetailVo vo = BeanUtil.toBean(device,DeviceDetailVo.class);
        vo.setDeviceStatus(status);
        if (ObjectUtil.isNotEmpty(activeTime)) {
            //转换时间格式
            LocalDateTime time = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            vo.setActiveTime(DateTimeZoneConverter.utcToShanghai(time));
        }
        return vo;
    }

    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        List<Map<String,Object>> list = new ArrayList<>();
        //从华为云获取数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        //发起请求,得到响应数据
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        //进行判断,如果返回值不为200就返回一个空集合
        if (response.getHttpStatusCode()!=200) {
            return Collections.emptyList();
        }
        DeviceShadowData deviceShadowData = null;
        //对获取数据进行抓异常,有可能返回一个空列表
        try {
            deviceShadowData = response.getShadow().get(0);
        } catch (Exception e) {
            return Collections.emptyList();
        }
        //得到对象中嵌套的对象
        DeviceShadowProperties reported = deviceShadowData.getReported();
        //构建时间对象
        String eventTime = reported.getEventTime();
        LocalDateTime time = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        JSONObject entries = JSONUtil.parseObj(reported.getProperties());
        //对解析过的对象进行遍历,封装数据
        entries.forEach((key, value) ->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",key);
            map.put("value",value);
            map.put("eventTime",time);
            list.add(map);
        });
        return list;
    }

    /**
     * 更新设备
     * @param dto
     */
    @Override
    public void updateDeviceInfo(DeviceDto dto) {
        //判断当前同一位置是否绑定了相同的产品
        checkSameLocationIsOrNotBingdingSameDevice(dto);
        //查询数据库,判断当前deviceName是否进行修改,进行修改则调用华为云接口
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, dto.getIotId()));
        if(device.getDeviceName()!=dto.getDeviceName()){
            //调用华为云修改接口
            UpdateDeviceRequest request = new UpdateDeviceRequest();
            request.setDeviceId(dto.getIotId());
            UpdateDevice body = new UpdateDevice();
            body.setDeviceName(dto.getDeviceName());
            request.setBody(body);
            UpdateDeviceResponse updateDeviceResponse = client.updateDevice(request);
            if(updateDeviceResponse.getHttpStatusCode()!=200){
                throw new BaseException("网络开小差了");
            }
        }
        Device device1 = BeanUtil.toBean(dto, Device.class);
        this.updateById(device1);
    }

    /**
     * 删除设备
     * @param iotId
     */
    @Override
    public void deleteDevice(String iotId) {
        //封装请求参数
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        //判断返回码,如果成功则修改数据库
        if(response.getHttpStatusCode()!=204 && response.getHttpStatusCode()!=404){
            throw new BaseException("网络开小差了");
        }
        //修改数据库
        boolean result = this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(!result){
            throw new BaseException("删除失败");
        }
    }

    @Override
    public AjaxResult queryProduct(String productKey) {
        if (ObjectUtil.isEmpty(productKey)) {
            throw new BaseException("参数不能为空");
        }
        //调用华为云接口查询产品信息
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse showProductResponse = client.showProduct(request);
        if (showProductResponse.getHttpStatusCode()!=200) {
            throw new BaseException("网络开小差了");
        }
        List<ServiceCapability> serviceCapabilities = showProductResponse.getServiceCapabilities();
        if (CollUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(serviceCapabilities);
    }

    /**
     * 判断当前同一位置是否绑定了相同的产品
     * @param dto
     */
    private void checkSameLocationIsOrNotBingdingSameDevice(DeviceDto dto) {
        //判断同一位置是否绑定了相同的产品
        Long count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.productKey)//相同产品
                .eq(Device::getBindingLocation, dto.getBindingLocation())//相同绑定位置
                .eq(Device::getLocationType, dto.getLocationType())//相同位置类型
                .eq(ObjectUtil.isNotEmpty(dto.getPhysicalLocationType()),Device::getPhysicalLocationType, dto.getPhysicalLocationType())//相同物理位置类型
                .ne(ObjectUtil.isNotEmpty(dto.getIotId()),Device::getIotId,dto.getIotId()));//如果前端没传iotId说明是新增,反之为修改,排除当前设备
        if(count >0){
            throw new BaseException("设备重复,无法申请");
        }
    }

}
